/**
 * RessourceManager - Singleton
 * Load image ressource from twitter
 * @version 1.0
 * @author DavidRonai ( Makio ) http://flash-dungeon.com
 */

var RessourceManager =(function()
{
	var instance;
	
	function init ()
	{
		//- PRIVATE VAR ---------------------------------
		var friendLoaded = false;
		var allLoaded = false;
		var colladaLoaded = 0;
		var imageLoaded = 0;
		var imageLoadedTry = 0;
		
		MAX_FOLLOWERS_ID = 12;
		MAX_FFRIENDS_ID = 3;
		MAX_TRY = 2;
		
		var models = [];
		
		//- PRIVATE FUNCTION ----------------------------	
		
		function startLoadFollower()
		{
			$.ajax({
			  url: "https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name="+userName,
			  dataType: "jsonp",
			  jsonpCallback: "followersIDCallback"
			}).error(function(){  });
		}
		
		function startLoadFriend(){
			$.ajax({
			  url: "https://api.twitter.com/1/friends/ids.json?cursor=-1&screen_name="+userName,
			  dataType: "jsonp",
			  jsonpCallback: "friendsIDCallback"
			}).error(function(){  });
		}

		function loadImage(array)
		{
			if(allLoaded)
				return;
				
			//excess the limit of try
			if(imageLoadedTry >= MAX_TRY)
			{
				imageLoadedTry = 0;
				array.splice(imageLoaded,1);
				imageLoaded++;
			}
			
			//continue the loading
			if(imageLoaded < array.length)
			{
				var urlServer = (imageLoadedTry==0)?URL_SERVER:"//img-to-json.appspot.com/";
				var data = array[imageLoaded];
				$.getImageData({
					url: data.imageURL,
					server: urlServer,
					success: function(image)
					{
						if(array[imageLoaded].image==null)
						{
							array[imageLoaded].image = image; 
							imageLoaded++;
							imageLoadedTry = 0;
							loadImage(array);
							var percent = .2;
							if(friendLoaded){
								percent+=.4;
								percent+=imageLoaded/MAX_FOLLOWERS_ID*.4;
							} else {
								percent+=imageLoaded/MAX_FFRIENDS_ID*.4;
							}
							if(percent<1 && !allLoaded){
								instance.percent = percent;
								if(instance.onProgress != null)
									instance.onProgress(percent);
							}
						}
					},
					error: function(xhr, text_status){
						imageLoadedTry++;
						loadImage(array); //sometimes need more than one request on the image..
					}
				});
			}
			
			//call the onComplete if all is Loaded
			else 
			{
				if(!friendLoaded){
					friendLoaded = true;
					imageLoaded = 0;
					imageLoadedTry = 0;
					loadImage(instance.followers);
				} else {
					allLoaded = true;
					instance.percent = 1;
					if(instance.onComplete!=null)
						instance.onComplete();
				}
			}
		}
		
		return {
			
			//- public var -----------------------------------------
			
			followersID : [],
			followers : [],
			friendsID : [],
			friends : [],
			onComplete:null,
			onProgress:null,
			percent: 0,
			
			//- public function ------------------------------------
			load:function()
			{
				startLoadFollower();
			},
			
			followersIDCallback : function (data)
			{
				followersID = data.ids.sort( randOrd ); //randomize the order
				
				if(followersID.length == 0) {
					alert("no followers");
				}
				
				var urlFollowers = "https://api.twitter.com/1/users/lookup.json?user_id="+followersID[0];
				
				for( var i = 1; i < MAX_FOLLOWERS_ID && i < data.ids.length; i++ ){
					urlFollowers+=","+followersID[i];
				}
				
				urlFollowers += "&include_entities=false";
				instance.percent = .05;
				if(instance.onProgress!=null)
					instance.onProgress(instance.percent);
				
				$.ajax({
				  url: urlFollowers,
				  dataType: "jsonp",
				  jsonpCallback: "followersCallback"
				}).error(function(){  });
			},
		
			followersCallback : function (data)
			{
				for( var i=0; i < data.length; i++ )
				{
					RessourceManager.getInstance().followers[i] = minimizeData(data[i]);
				}
				instance.percent = .1;
				if(instance.onProgress)
					instance.onProgress(instance.percent);
				startLoadFriend();
			},

			friendsIDCallback :function (data)
			{
				friendsID = data.ids.sort( randOrd );
				
				if(friendsID.length == 0){
					alert("no friends");
				}
				
				var url = "https://api.twitter.com/1/users/lookup.json?user_id="+friendsID[0];
				for(var i = 1; i < MAX_FFRIENDS_ID && i < data.ids.length; i++){
					url+=","+friendsID[i];
				}
				url += "&include_entities=false";
				
				instance.percent = .15;
				if(instance.onProgress!=null)
					instance.onProgress(instance.percent);
				$.ajax({
				  url: url,
				  dataType: "jsonp",
				  jsonpCallback: "friendsCallback"
				}).error(function(){  });
			},

			friendsCallback:function (data)
			{
				for( var i=0; i < data.length; i++ )
				{
					RessourceManager.getInstance().friends[i] = minimizeData(data[i]);
				}
				
				instance.percent = .2;
				if(instance.onProgress)
					instance.onProgress(instance.percent);
				
				imageLoaded = 0;
				loadImage(RessourceManager.getInstance().friends);
			}
		}
		
		//- PRIVATE UTILS ----------------------------	
		
		/**
		 * Use for randomize an array
		 */
		function randOrd(){ 
			return (Math.round(Math.random())-0.5); 
		}

		/**
		 * keep only important information
		 */		
		function minimizeData(data)
		{
			o = {};
			o.id = data.id;
			o.name = data.name;
			o.imageURL = data.profile_image_url;
			o.image = null;
			o.followers = data.followers_count;
			o.friends = data.friends_count;
			o.lang = data.lang;
			o.location = data.location;
			o.tweetsNumber = data.statuses_count;
			return o;
		}
	}
 
	return {
		getInstance :function(){
			if (!instance){
				instance = init();
			}
			return instance; 
		}
	}
})();

//Warpper
function followersIDCallback(data) { RessourceManager.getInstance().followersIDCallback(data); }
function followersCallback(data) { RessourceManager.getInstance().followersCallback(data); }
function friendsIDCallback(data) { RessourceManager.getInstance().friendsIDCallback(data); }
function friendsCallback(data) { RessourceManager.getInstance().friendsCallback(data); }
